<?php
namespace frame\libs;
use frame\libs\PDOWrapper;

/**
 * 基础模型
 */
class BaseModel
{
    protected $pdo = null;
    protected $db_name;
    protected $table;

    public function __construct()
    {
        $this->pdo = new PDOWrapper($this->db_name);
    }

    public static function getInstance()
    {
        //获取静态化调用的类名
        $modelClassName = get_called_class();
        return new $modelClassName;
    }

    public function fetchAll($sql, $params=array())
    {
        return $this->pdo->fetchAll($sql, $params);
    }

    public function fetchOne($sql, $params=array())
    {
        return $this->pdo->fetchOne($sql, $params);
    }

    public function delete($sql, $params=array())
    {
        return $this->pdo->exec($sql, $params); 
    }

    public function update($sql, $params=array())
    {
        return $this->pdo->exec($sql, $params);
    }

    public function rowCount($sql, $params=array())
    {
        return $this->pdo->rowCount($sql, $params);
    }

    public function insert($params=array())
    {
        $fields = '';
        $values = '';
        foreach ($params as $key => $value) {
            $fields .= "`$key`,";
            $values .= ":$key,";
        }
        $fields = rtrim($fields, ',');
        $values = rtrim($values, ',');
        $sql = "INSERT INTO `{$this->table}`($fields) VALUES ($values)";
        return $this->pdo->exec($sql, $params);
    }

    public function lastInsertId()
    {
        return $this->pdo->lastInsertId();
    }

    public function beginTransaction()
    {
        return $this->pdo->beginTransaction();
    }

    public function commit()
    {
        return $this->pdo->commit();
    }

    public function rollBack()
    {
        return $this->pdo->rollBack();
    }
}